<!--
 * @Author: your name
 * @Date: 2020-09-14 11:01:03
 * @LastEditTime: 2021-04-21 10:41:11
 * @LastEditors: Please set LastEditors
 * @Description:登录页面包含登录-注册-找回密码，三个模块
 * @FilePath: \face-recognition\src\views\Login\index.html
-->
<style lang="less" scoped>
.login {
  width: 100vw;
  height: 100vh;
  background: url("../../assets/img/init.jpg") top center no-repeat;
  background-size: cover;
  .login_box {
    background: rgba(255, 255, 255, 0.8);
    border-radius: 8px;
    position: fixed;
    top: 15%;
    right: 10%;
    padding: 25px;
    box-shadow: 0 0 20px #fff;
    .logo {
      text-align: center;
      h2 {
        font-size: 24px;
        padding-top: 20px;
        padding-bottom: 40px;
      }
    }
  }
}
.b_router {
  display: flex;
  justify-content: space-between;
  span {
    opacity: 0.8;
    cursor: pointer;
    color: #333;
    transition: all 0.4s;
    &:hover {
      color: #409eff;
      opacity: 1;
    }
  }
}
/deep/.el-form-item__label {
  font-size: 17px;
  line-height: 40px;
}
/deep/ .el-input__inner {
  height: 40px;
  line-height: 40px;
  width: 280px;
  background: rgba(255, 255, 255, 0.8);
}
/deep/.el-form-item__label {
  color: #333;
}
.bn {
  /deep/.el-form-item__content {
    margin: 0 !important;
  }
}
.authCode {
  width: 160px;
  /deep/.el-input__inner {
    width: 160px;
  }
}
.authCode_btn {
  margin-left: 5px;
  padding: 10px 8px;
  position: relative;
}
.verify_code {
  margin-left: 10px;
    width: 120px;
    height: 38px;
    cursor: pointer;
    display: inline-block;
   vertical-align: top;
   border-radius: 4px;
  border: 1px solid #b9b9b9;
  img {
    width: 120px;
    height: 38px;
  }
}
.verifyCode1 {
  display: none;
  /deep/.el-input__inner,.code_npt {
width: 144px;
  }
}
/deep/.el-loading-spinner .circular {
  width: 30px;
  height: 30px;
}
/deep/.el-loading-spinner {
  margin-top: -15px;
}
@media screen and(min-device-width: 1360px) and(max-device-width: 1366px) {
  .login_box {
    transform: scale(.8);
    top:8%!important
  }
}
</style>
<template>
  <div class="login">
    <div class="login_box">
      <div class="logo">
        <img width="150" src="../../assets/img/logo.png" />
        <h2>{{ tit.tit }}</h2>
      </div>
<!-- ############################################### 登录 ####################################################### -->
      <div class="login_init" v-if="init.login_init">
        <el-form :model="login" ref="login_form" label-width="auto" class="login_form" :rules="login.rules" hide-required-asterisk>
          <el-form-item label="用户名:" prop="username" style="width:340px">
            <el-input type="text" maxlength="19" v-model.trim="login.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label=" 密码:" prop="password">
            <el-input type="password" :show-password="true" v-model.trim="login.password" maxlength="19" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item label="验证码:" prop="verifyCode" class="verifyCode1">
            <el-input type="text" v-model.trim="login.verifyCode" maxlength="10" placeholder="请输入图形验证码" class="code_npt"></el-input>
            <span v-loading="verifyCodeLoading1" class="verify_code"><img :src="verifyCodeUrl_1" @click="verifyCodeHandle1"></span>
          </el-form-item>
          <el-form-item class="bn">
            <el-button :loading="login.loginSucces" type="primary" @click="loginHandler('login_form')" style="width:100%">登录</el-button>
          </el-form-item>
        </el-form>
        <p class="b_router">
          <span @click="goresetPsw">忘记密码？</span>
          <span @click="goRegister">去注册</span>
        </p>
      </div>
      
<!-- ############################################### 注册 ####################################################### -->
      <div class="register_init" v-show="init.register_init">
        <el-form :model="register" ref="register_form" label-width="auto" class="register_form" :rules="register.rules" hide-required-asterisk label-position="right">
          <el-form-item label="用户名:" prop="username">
            <el-input type="text" v-model.trim="register.username" maxlength="19" placeholder="数字和字母组合"></el-input>
          </el-form-item>
          <el-form-item label="邮箱:" prop="email">
            <el-input type="text" v-model.trim="register.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
          <el-form-item label="密码:" prop="password">
            <el-input type="password" :show-password="true" v-model.trim="register.password" maxlength="16" placeholder="请输入大于6位数字和字母组合的密码"></el-input>
          </el-form-item>
          <el-form-item label="确认密码:" prop="checkPsw">
            <el-input type="password" :show-password="true" v-model.trim="register.checkPsw" placeholder="请再次输入密码"></el-input>
          </el-form-item>
          <el-form-item label="验证码:" prop="verifyCode" class="verifyCode1">
            <el-input type="text" v-model.trim="register.verifyCode" maxlength="10" placeholder="请输入图形验证码" class="code_npt"></el-input>
            <span v-loading="verifyCodeLoading1" class="verify_code"><img :src="verifyCodeUrl_2" @click="verifyCodeHandle2"></span>
          </el-form-item>
          <el-form-item class="bn">
            <el-button :loading="register.registerSucces" type="primary" @click="registerHandler('register_form')" style="width:100%">注册</el-button>
          </el-form-item>
        </el-form>
        <p class="b_router">
          <span @click="goresetPsw">忘记密码？</span>
          <span @click="goLogin">去登录</span>
        </p>
      </div>

<!-- ############################################### 找回密码 ####################################################### -->
      <div class="resetPsw_init" v-show="init.resetPsw_init">
        <el-form :model="resetPsw" ref="resetPsw_form" label-width="auto" class="resetPsw_form" :rules="resetPsw.rules" hide-required-asterisk>
          <el-form-item label="用户名:" prop="username"><el-input type="text" maxlength="19" v-model.trim="resetPsw.username" placeholder="请输入用户名"></el-input></el-form-item>
          <el-form-item
            label="邮箱:"
            prop="email"
            :rules="[
            { required: true, message: '请输入邮箱地址'},
            {
              type: 'email',
              message: '请输入正确的邮箱地址'
            }]"
          >
            <el-input type="text" v-model.trim="resetPsw.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
          <el-form-item label="邮箱验证码:" prop="authCode">
            <el-input type="text" v-model.trim="resetPsw.authCode" placeholder="请输入邮箱验证码" class="authCode"></el-input>
            <el-button type="primary" class="authCode_btn" :disabled="resetPsw.authCodeBtnStatus" @click="getauthCodeHandler('resetPsw_form')">{{ resetPsw.authCodeTxt }}</el-button>
          </el-form-item>
          <el-form-item label="新密码:" prop="password">
            <el-input type="password" :show-password="true" v-model.trim="resetPsw.password" maxlength="16" placeholder="请输入大于6位数字和字母组合的密码"></el-input>
          </el-form-item>
          <el-form-item label="确认密码:" prop="checkPsw">
            <el-input type="password" :show-password="true" v-model.trim="resetPsw.checkPsw" placeholder="请再次输入密码"></el-input>
          </el-form-item>
          <el-form-item label="图形验证码:" prop="verifyCode" class="verifyCode1">
            <el-input type="text" v-model.trim="resetPsw.verifyCode" maxlength="10" placeholder="请输入图形验证码" class="code_npt" @click.native="verifyCodeHandle3"></el-input>
            <span v-loading="verifyCodeLoading3" class="verify_code"><img :src="verifyCodeUrl_3" @click="verifyCodeHandle3"></span>
          </el-form-item>
          <el-form-item class="bn">
            <el-button :loading="resetPsw.resetPswSucces" type="primary" @click="resetPswHandler('resetPsw_form')" style="width:100%">确认</el-button>
          </el-form-item>
       
        </el-form>
        <p class="b_router">
          <span @click="goRegister">去注册</span>
          <span @click="goLogin">去登录</span>
        </p>
      </div>
    </div>
  </div>
</template>

<script>
import {verifycode, isUser, isEmail, regist, login, getAuthCode, resetpassword} from "@/api/user"
import { mapState, mapMutations, mapGetters } from "vuex"
// import cookies from "js-cookie"
// import encrypt from "@/utils/encrypt";  //加密
export default {
  data() {
    // 用户名自定义验证
    let validateName = (rule, value, callback) => {
      value === ""
        ? callback(new Error("请输入用户名"))
        : !this.nameReg.test(value)
        ? ''
        //  callback(new Error("用户名必须为数字和字母组合大于3个字符"))
        : callback()
      callback()
    }

    // 注册判断用户名是否可用
    let validateName1 = (rule, value, callback) => {
      value === ""
        ? callback(new Error("请输入用户名"))
        : !this.nameReg.test(value)
        ? callback(new Error("用户名必须为数字和字母组合"))
        : this.isUserHandler().then((res) => {
            !res
              ? callback(
                  new Error("用户名已存在"),
                  this.$message({
                    message: "用户名已存在",
                    type: "warning",
                    duration: 3 * 1000,
                  })
                )
              : callback()
          })
    }
    // 注册判断邮箱是否可用
    let validate_registerEmail = (rule, value, callback) => {
      this.isEmail().then((res) => {
        !res
          ? callback(
              new Error("邮箱已存在"),
              this.$message({
                message: "邮箱已存在",
                type: "warning",
                duration: 3 * 1000,
              })
            )
          : callback()
      })
    }

    // 注册密码-密码自定义验证
    let validatePsw_regist = (rule, value, callback) => {
      value === ""
        ? callback(new Error("请输入密码"))
        : !this.pswReg.test(value)
        ? callback(new Error("请输入大于6位数字和字母组合的密码"))
        : this.register.checkPsw !== ""
        ? this.$refs.register_form.validateField("checkPsw")
        : callback()
      callback()
    }
    let validatePsw1_regist = (rule, value, callback) => {
      value === ""
        ? callback(new Error("请再次输入密码"))
        : value !== this.register.password
        ? callback(new Error("两次输入密码不一致!"))
        : callback()
      callback()
    }
    // 找回密码-密码自定义验证
    let validatePsw_reset = (rule, value, callback) => {
      value === ""
        ? callback(new Error("请输入密码"))
        : !this.pswReg.test(value)
        ? callback(new Error("请输入大于6位数字和字母组合的密码"))
        : this.resetPsw.checkPsw !== ""
        ? this.$refs.resetPsw_form.validateField("checkPsw")
        : callback()
      callback()
    }
    let validatePsw1_reset = (rule, value, callback) => {
      value === ""
        ? callback(new Error("请再次输入密码"))
        : value !== this.resetPsw.password
        ? callback(new Error("两次输入密码不一致!"))
        : callback()
      callback()
    }
    return {
      isDomAlive: false,
      // 标题
      tit: {
        tit: "欢迎登录人脸辨识云",
        tit_login: "欢迎登录人脸辨识云",
        tit_register: "欢迎注册人脸辨识云",
        tit_find: "找回密码",
      },
      init: {
        login_init: true,
        register_init: false,
        resetPsw_init: false,
      },
//验证码图片
      verifyCodeUrl_1: '', 
      verifyCodeUrl_2: '', 
      verifyCodeUrl_3: '', 
      verifyCodeLoading1: false,
      verifyCodeLoading2: false,
      verifyCodeLoading3: false,
// ------------------------------------登录------------------------------
      login: {
        username: "zhanglong123",
        password: "12345qwe",
        verifyCode: '111',
        rules: {
          username: [{ validator: validateName, trigger: "blur" }],
          password: [{ required: true, message: "密码不能为空", trigger: "blur" }],
          verifyCode: [{ required: true, message: "验证码不能为空", trigger: "blur" }]
        },
        // loginSucces: true
      },
 // -----------------------------------注册------------------------------
      register: {
        username: "",
        email: "",
        password: "",
        checkPsw: "",
        verifyCode: '111',
        rules: {
          username: [
            { required: true, validator: validateName1, trigger: "blur" },
          ],
          password: [{ validator: validatePsw_regist, trigger: "blur" }],
          checkPsw: [{ validator: validatePsw1_regist, trigger: "blur" }],
          email: [
            { required: true, message: "请输入邮箱地址", trigger: "blur" },
            {
              type: "email",
              message: "请输入正确的邮箱地址",
              trigger: ["blur", "change"],
            },
            { validator: validate_registerEmail, trigger: "blur" },
          ],
          verifyCode: [{ required: true, message: "验证码不能为空", trigger: "blur" }]
        },
        // loginSucces: true
      },
// ----------------------------------=找回密码---------------------------------
      resetPsw: {
        authCodeBtnStatus: false,
        authCode_disabledTxt: "后重新获取",
        authCodeTxt: "获取验证码",
        authCodeTime: 60,
        // username: "zhanglong123",
        // email: "2823698322@qq.com",
        username: "",
        email: "",
        authCode: "",
        password: "",
        checkPsw: "",
        verifyCode: '111',
        rules: {
          username: [
            { required: true, validator: validateName, trigger: "blur" },
          ],
          password: [{ validator: validatePsw_reset, trigger: "blur" }],
          checkPsw: [{ validator: validatePsw1_reset, trigger: "blur" }],
          authCode: [{ required: true, message: "验证码不能为空", trigger: "blur" }],
          verifyCode: [{ required: true, message: "验证码不能为空", trigger: "blur" }]
        },
        // loginSucces: true
      },
    }
  },
  computed: {
    ...mapState({
      nameReg: (nameReg) => nameReg.loginModule.nameReg,
      pswReg: (pswReg) => pswReg.loginModule.pswReg,
    }),
  },

  methods: {
// 获取图片验证码 
    verifyCodeHandle1() {
      // this.getVerifyCode('verifyCodeLoading1', 'verifyCodeUrl_1')
    },
    verifyCodeHandle2() {
      // this.getVerifyCode('verifyCodeLoading2', 'verifyCodeUrl_2')
    },
    verifyCodeHandle3() {
      // this.getVerifyCode('verifyCodeLoading3', 'verifyCodeUrl_3')
    },
    getVerifyCode(loading, imgUrl) {
       this[loading] = true
       verifycode().then((res) => {
         if(res.size) {
         this[imgUrl] = location.origin + '/apis/api/user/verifycode?' + new Date().getTime()
        // console.log(window.URL.createObjectURL(new Blob([res.data])))
        this[loading] = false
         } else {
           this.$message({
                message: '请求超时，请刷新页面重试',
                type: "warning",
                duration: 5 * 1000,
              })
         }
       })
    },
    ...mapMutations(["setUser"]), //存储User
    ...mapMutations(["setToken"]), //存储token
    // 判断用户名是否可用
    isUserHandler() {
      let _this = this
      return isUser(this.register.username).then((res) => {
        return res.data ? true : false
      })
    },
    // 判断邮箱是否可用
    isEmail() {
      let _this = this
      return isEmail(this.register.email).then((res) => {
        return res.data ? true : false
      })
    },
    
// -------------------------------------注册----------------------------------
    registerHandler(registRule) {
      this.$refs[registRule].validate((valid) => {
        if (valid) {
          let param = new FormData()
              param.append('username',this.register.username)
              param.append('email',this.register.email)
              param.append('password',this.register.password)
              param.append('nickname',this.register.username)
          regist(param).then((res) => {
            if (res.code == 0 && res.data) {
// 登录
               param.delete('email')
               param.delete('nickname')
              login(param).then((res1) => {
                if (res1.code == 0) {
                  this.$message.success('注册成功,系统已自动为您登录')
                  this.setUser(res1.data)  
                  this.setToken(res1.data.token) 
                  this.$router.push("/home")
                } else {
                  if(res1.code == 5001) {
                    this.$message.success('注册成功，请登录', 5000)
                    this.init.resetPsw_init = this.init.register_init = false
                    this.init.login_init = true
                    this.tit.tit = this.tit.tit_login
                  } 
                }
              })
            } else {
              this.$message.warning('注册失败，请稍后重试', 5000)
            }
          })
        }
      })
    },
// -------------------------------------------登录----------------------------------
    loginHandler(loginRule) {
      let _this = this,
          param = new FormData()
          param.append('username', this.login.username)
          param.append('password', this.login.password)
      this.$refs[loginRule].validate((valid) => {
        if (valid) {
          // {
          //    username: this.login.username,
          //    password: this.login.password
          // }
          login(
             {
               username: this.login.username,
               password: this.login.password
             }
          ).then((res) => {
            if (res.code == 0 && res.data && res.data.username) {
              this.$message.success('登录成功')
              this.setUser(res.data)
              this.setToken(res.data.token) 
              this.$router.push("/home")
            } 
            // else {
            //   this.$message({
            //     message: res.msg,
            //     type: "warning",
            //     duration: 5 * 1000,
            //   })
            //    this.verifyCodeHandle1()
            // }  
          })
        }
      })
    },

// -----------------------------------找回密码--------------------------------------

   // 找回密码-获取邮箱验证码-----------------------
    getauthCodeHandler(resetPsw) {
      let _this = this
      let timeDecrease = this.resetPsw.authCodeTime
      this.$refs[resetPsw].validateField("username", (validName) => {
        if (!validName) {
          this.$refs[resetPsw].validateField("email", (validEmail) => {
            if (!validEmail) {
               let param = new FormData()
                   param.append('username',_this.resetPsw.username)
                   param.append('email',_this.resetPsw.email)
// 发送验证码

              getAuthCode(param).then((res) => {
                if (res.code == 0 && res.data) {
                  authCodeHandler()
                } 
                // else {
                //   _this.$message.warning('验证码发送失败，请稍后重试', 5000)
                // }
              })
            }
          })
        }
      })
      function authCodeHandler() {
        let timer = setInterval(() => {
          timeDecrease--
          if (!timeDecrease <= 0) {
            _this.resetPsw.authCodeTxt =
              timeDecrease + "s" + _this.resetPsw.authCode_disabledTxt
            _this.resetPsw.authCodeBtnStatus = true
          } else {
            clearInterval(timer)
            _this.resetPsw.authCodeTxt = "获取验证码"
            _this.resetPsw.authCodeBtnStatus = false
          }
        }, 1000)
        new Promise((resolved) => {
          if (timeDecrease != 58) resolved()
        }).then(() => {
            _this.$message.success('验证码已发送至邮箱，请注意查收', 5000)
          // sessionStorage.setItem("authCode", true) //标识验证码已发送
        })
      }
    },
// 找回密码-提交-直接登录
    resetPswHandler(resetPsw) {
      let _this = this
      _this.$refs[resetPsw].validate((valid) => {
        if (valid) {
          // 发送验证码后再次确认邮箱和用户名可用否
          isUser(this.resetPsw.username).then((res) => {
            if (!res.data) {
              isEmail(this.resetPsw.email).then((res1) => {
                if (!res1.data) {
                  startResetPsw()
                } else {
                  this.$message.warning('邮箱不存在', 3000)
                }
              })
            } else {
               this.$message.warning('用户名不存在', 3000)
            }
          })
          function startResetPsw() {
             let param = new FormData()
                 param.append('username',_this.resetPsw.username)
                 param.append('email',_this.resetPsw.email)
                 param.append('password',_this.resetPsw.password)
                 param.append('token',_this.resetPsw.authCode)
            resetpassword(param).then((res2) => {
              if (res2.code == 0 && res2.data) {
 // 重置密码后-直接登录

               param.delete('email')
               param.delete('token')
              login(param).then((res3) => {
                if (res3.code == 0 && res3.data && res3.data.username) {
                  _this.$message({
                    message: "密码重置成功,系统已自动为您登录",
                    type: "success",
                  })
                  console.log(res3)
                   _this.setUser(res3.data)
                   _this.setToken(res3.data.token)
                  _this.$router.push("/home")
                } else {
                  if(res3.code == 5001) {
                     _this.$message({
                        message: "重置密码成功，请登录",
                        type: "success",
                        duration: 4 * 1000,
                      })
                     _this.init.resetPsw_init = this.init.register_init = false
                      _this.init.login_init = true
                      _this.tit.tit = _this.tit.tit_login
                  } 
                }
              })
              } else if (res2.code == 400) {
                _this.$message({
                  message: "请输入有效验证码！",
                  type: "warning",
                  duration: 5 * 1000,
                })
              }
            })
          }
        }
      })
    },
    // 按钮
    // 去注册
    goRegister() {
      let t = this.init
      t.login_init = t.resetPsw_init = false
      t.register_init = true
      this.tit.tit = this.tit.tit_register
    },
    // 去登录
    goLogin() {
      let t = this.init
      t.register_init = t.resetPsw_init = false
      t.login_init = true
      this.tit.tit = this.tit.tit_login
    },
    // 找回密码
    goresetPsw() {
      let t = this.init
      t.login_init = t.register_init = false
      t.resetPsw_init = true
      this.tit.tit = this.tit.tit_find
    },
  },
  mounted() {
    let _this = this
       this.$nextTick(() => {
// AES加密
    // let key = this.login.password//设置密钥
    // let a = this.login.password = encrypt.Encrypt(this.login.password, key);//加密
    // let psd = encrypt.Decrypt(this.login.password, key);//解密
// 屏蔽验证码
        //  _this.verifyCodeHandle1()
        //  _this.verifyCodeHandle2()
        //  _this.verifyCodeHandle3()
       })
       
  },
 
}

</script>